/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mohammedalaa.valuecounterlib;

import ohos.agp.components.Attr;
import ohos.agp.components.AttrSet;

import java.util.Optional;

/**
 * Attr Utils
 */
public class AttrSetUtils {
    /**
     * get int
     *
     * @param attrSet      AttrSet
     * @param attrName     String
     * @param defaultValue int
     * @return Integer
     */
    public static Integer getIntegerFromTypedArray(AttrSet attrSet, String attrName, int defaultValue) {
        if (attrSet == null || attrName == null || attrName.isEmpty()) {
            return defaultValue;
        }
        Optional<Attr> attrOptional = attrSet.getAttr(attrName);
        if (attrOptional == null || !attrOptional.isPresent()) {
            return defaultValue;
        }
        return attrOptional.get().getIntegerValue();
    }

    /**
     * get Dimension
     *
     * @param attrSet          AttrSet
     * @param attrName         String
     * @param defaultDimension int
     * @return Integer
     */
    public static Integer getDimensionFromTypedArray(AttrSet attrSet, String attrName, int defaultDimension) {
        if (attrSet == null || attrName == null || attrName.isEmpty()) {
            return defaultDimension;
        }
        Optional<Attr> attrOptional = attrSet.getAttr(attrName);
        if (attrOptional == null || !attrOptional.isPresent()) {
            return defaultDimension;
        }
        return attrOptional.get().getDimensionValue();
    }

    /**
     * get Color
     *
     * @param attrSet      AttrSet
     * @param attrName     String
     * @param defaultColor int
     * @return Integer
     */
    public static Integer getColorFromTypedArray(AttrSet attrSet, String attrName, int defaultColor) {
        if (attrSet == null || attrName == null || attrName.isEmpty()) {
            return defaultColor;
        }
        Optional<Attr> attrOptional = attrSet.getAttr(attrName);
        if (attrOptional == null || !attrOptional.isPresent()) {
            return defaultColor;
        }
        return attrOptional.get().getColorValue().getValue();
    }
}
